<?php

/**
 * @author Huy <www.imhuy.com>
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 */


class ModelLoaderComponent extends Object
{
    
    var $controller = null;
    
    function startup(&$controller)
    {
        $this->setController($controller);
    }
    /**
     * Load the model and assign it to the controller
     *
     * @access public
     * @param string $modelClass
     * @return bool | mixed
     */
    function load($modelClass, $objectName = null)
    {
        if (!$this->controller)
        {
            return false;
        }
        
        
        $id = false;
        $object = null;
        $cached = false;
        
        $plugin = '';
        
        if ($this->controller->plugin) 
        {
            $plugin = $this->controller->plugin . '.';
        }
        
        if (!class_exists($modelClass))
        {
            loadModel($plugin . $modelClass);
        }
        
        if (class_exists($modelClass))
        {
            if (!$objectName)
            {
                $objectName = $modelClass;
            }
            
            if ($this->controller->persistModel)
            {
                $cached = $this->_persist($modelClass, null, $object);
            }
            
            if (false === $cached)
            {
                $model =& new $modelClass($id);
                $this->controller->modelNames[] = $modelClass;
                $this->controller->{$objectName} =& $model;
                
                if ($this->controller->persistModel === true) 
                {
                    $this->_persist($modelClass, true, $model);
                    $registry = ClassRegistry::getInstance();
                    $this->_persist($modelClass . 'registry', true, $registry->__objects, 'registry');
                }
                
            }
            else
            {
                $this->_persist($modelClass . 'registry', true, $object, 'registry');
                $this->_persist($modelClass, true, $object);
                $this->controller->{$objectName} = $this->{$modelClass};
                
                // unset the temp model, for PHP4 
                unset($this->{$modelClass});
                $this->controller->modelNames[] = $modelClass;
            }
        }
        else
        {
            return $this->controller->cakeError('missingModel', array(array('className' => $modelClass, 'webroot' => '', 'base' => $this->controller->base)));
        }
        return true;
    }
    
    /**
     * Set the controller to work
     *
     * @access public
     * @param AppController $controller
     * @return void
     */
    function setController(&$controller)
    {
        $this->controller = $controller;
    }
}
?>